package org.jeecg.modules.xxgx.spgl.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.ListUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.common.util.LoginUserUtil;
import org.jeecg.modules.common.util.StringUtilsExt;
import org.jeecg.modules.xxgx.spgl.entity.CsXxProduct;
import org.jeecg.modules.xxgx.spgl.mapper.CsXxProductMapper;
import org.jeecg.modules.xxgx.spgl.service.ICsXxProductService;
import org.jeecg.modules.xxgx.spgl.vo.CsXxProductEditSlvBatchParam;
import org.jeecg.modules.xxgx.spgl.vo.CsXxProductPlfmParam;
import org.jeecg.modules.xxgx.spgl.vo.CsXxProductPlznfmParam;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 商品
 * @Author: jeecg-boot
 * @Date:   2023-08-21
 * @Version: V1.0
 */
@Service
public class CsXxProductServiceImpl extends ServiceImpl<CsXxProductMapper, CsXxProduct> implements ICsXxProductService {

    @Transactional
    @Override
    public void updateProductSlvBatch(CsXxProductEditSlvBatchParam csXxProductEditSlvBatchVO) {
        List<String> spidList = csXxProductEditSlvBatchVO.getSpid();

        List<CsXxProduct> list = new ArrayList<>();
        CsXxProduct csXxProduct;
        for(String spid : spidList) {
            csXxProduct = new CsXxProduct();
            csXxProduct.setId(spid);
            csXxProduct.setTax(csXxProductEditSlvBatchVO.getTax());
            list.add(csXxProduct);
        }
        this.updateBatchById(list);
    }

    @Transactional
    @Override
    public void updateProductPlfmBatch(CsXxProductPlfmParam csXxProductPlfmParam) {
        List<String> spidList = csXxProductPlfmParam.getSpid();

        List<CsXxProduct> list = new ArrayList<>();
        CsXxProduct csXxProduct;
        for(String spid : spidList) {
            csXxProduct = new CsXxProduct();
            csXxProduct.setId(spid);
            csXxProduct.setSpbm(csXxProductPlfmParam.getSsbm());
            csXxProduct.setSpssjc(csXxProductPlfmParam.getSpssjc());
            list.add(csXxProduct);
        }
        this.updateBatchById(list);
    }

    @Transactional
    @Override
    public void updateProductPlznfmBatch(List<CsXxProductPlznfmParam> csXxProductPlznfmParamList) {
        List<CsXxProduct> csXxProductList = new ArrayList<>();
        CsXxProduct csXxProduct;
        for(CsXxProductPlznfmParam plznfmParam: csXxProductPlznfmParamList) {
            csXxProduct = new CsXxProduct();
            csXxProduct.setId(plznfmParam.getSpid());
            csXxProduct.setSpbm(plznfmParam.getSsbm());
            csXxProduct.setSpssjc(plznfmParam.getSpssjc());
            csXxProductList.add(csXxProduct);
        }
        this.updateBatchById(csXxProductList);
    }

    /**
     * 上传导入商品信息
     * @param list
     * @param sffg 商品名称重复时，是否覆盖
     */
    @Override
    public Result<String> uploadProduct(List<CsXxProduct> list, String sffg) {
        String companyId = LoginUserUtil.getQyxxByLoginUser().getId();

        //校验格式
        int hh = 3;//表头占两行，excel中从第三行开始是数据行
        for(CsXxProduct csXxProduct : list) {
            if(StringUtils.isEmpty(csXxProduct.getSpmc())) {
                return Result.error("第" + hh + "行：商品名称不能为空");
            }

            /**
             * 判断使用优惠政策标识
             */
            String syybzcStr =csXxProduct.getYhzcbs();
            syybzcStr = syybzcStr.indexOf(".0000")>=0 ? syybzcStr.substring(0,1) : syybzcStr;
            syybzcStr = syybzcStr.replaceAll(" ","");
            if( "是".equals(syybzcStr) || "否".equals(syybzcStr) || "1".equals(syybzcStr) || "0".equals(syybzcStr)){
                //判断优惠政策是否为空
                if( ("是".equals(syybzcStr) || "1".equals(syybzcStr)) && org.springframework.util.StringUtils.isEmpty(csXxProduct.getZzstsgl()) ){
                    return Result.error("第" + hh + "行：使用了优惠政策，优惠政策不能为空");
                }
                //将使用优惠政策的 "是" "否" 转换为 1 0
                syybzcStr = "是".equals(syybzcStr) ? "1":"0";
                csXxProduct.setYhzcbs(syybzcStr);
            }else{
                return Result.error("第" + hh + "行：[优惠政策标识]内容为空或者不合法，请检查。");
            }

            /**
             * 判断免税类型
             */
            String mslxStr = csXxProduct.getLslbs();
            mslxStr = mslxStr.indexOf(".0000")>=0 ? mslxStr.substring(0,1) : mslxStr;
            mslxStr = mslxStr.replaceAll(" ","");
            if("正常税率".equals(mslxStr) || "免税".equals(mslxStr) || "不征增值税".equals(mslxStr) || "普通零税率".equals(mslxStr)
                    || "".equals(mslxStr) || "1".equals(mslxStr) || "2".equals(mslxStr) || "3".equals(mslxStr)){
                //将免税类型的 "正常税率" "免税" "不征增值税" "普通零税率" "" 1 2 3
                if("正常税率".equals(mslxStr)){
                    mslxStr = "";
                }else if ("免税".equals(mslxStr)){
                    mslxStr = "1";
                }else if ("不征增值税".equals(mslxStr)){
                    mslxStr = "2";
                }else if ("普通零税率".equals(mslxStr)){
                    mslxStr = "3";
                }
                csXxProduct.setLslbs(mslxStr);
            }else{
                return Result.error("第" + hh + "行：[免税类型]内容为空或者不合法，请检查。");
            }

            /**
             * 共享标志
             */
            String gxbzStr =csXxProduct.getGxbz();
            gxbzStr = gxbzStr.indexOf(".0000")>=0 ? gxbzStr.substring(0,1) : gxbzStr;
            gxbzStr = gxbzStr.replaceAll(" ","");
            if( "是".equals(gxbzStr) || "否".equals(gxbzStr) || "1".equals(gxbzStr) || "0".equals(gxbzStr)){
                gxbzStr = "是".equals(gxbzStr) ? "1":"0";
                csXxProduct.setGxbz(gxbzStr);
            }else{
                return Result.error("第" + hh + "行：[共享标志]内容为空或者不合法，请检查。");
            }

            csXxProduct.setCompanyId(companyId);

            //处理税收编码
            csXxProduct.setSpbm(operateSsbm(csXxProduct.getSpbm()));

            hh++;
        }

        //切分
        List<List<CsXxProduct>> partition = ListUtils.partition(list, 200);

        //提取需要插入的数据和需要更新覆盖的数据
        List<CsXxProduct> updateList = new ArrayList<>();
        List<CsXxProduct> insertList = new ArrayList<>();
        for(List<CsXxProduct> productList : partition){
            List<String> spdms = new ArrayList<>();
            List<String> spmcs = new ArrayList<>();

            productList.stream().forEach(m -> {
                if (!StringUtils.isEmpty(m.getSpdm())) {
                    spdms.add(m.getSpdm());
                } else if (!StringUtils.isEmpty(m.getSpmc()) && "1".equals(sffg)) {
                    spmcs.add(m.getSpmc());
                } else {
                    insertList.add(m);
                }
            });

            if (spdms.size() > 0) {
                List<CsXxProduct> spxxListBySpdm = this.baseMapper.selecSpxxtBySpdms(companyId, spdms);
                if (null == spxxListBySpdm || spxxListBySpdm.size() == 0) {
                    productList.stream().filter(spxx -> !StringUtils.isEmpty(spxx.getSpdm()))
                            .forEach(m -> insertList.add(m));
                } else {
                    productList.stream().filter(sp -> !StringUtils.isEmpty(sp.getSpdm())).forEach(m -> {
                        //如果商品自定义编码不为空 覆盖数据
                        CsXxProduct sp = spxxListBySpdm.stream().filter(spxx -> spxx.getSpdm().equals(m.getSpdm()))
                                .findAny().orElse(null);
                        if (null != sp) {
                            m.setId(sp.getId());
                            updateList.add(m);
                        } else {
                            insertList.add(m);
                        }
                    });
                }
            }

            if (spmcs.size() > 0) {
                List<CsXxProduct> spxxListBySpmc = this.baseMapper.selectSpBySpmcs(companyId, spmcs);
                if (null == spxxListBySpmc || spxxListBySpmc.size() == 0) {
                    productList.stream().filter(spxx -> StringUtils.isEmpty(spxx.getSpdm()) && !StringUtils.isEmpty(spxx.getSpmc()))
                            .forEach(m -> insertList.add(m));
                } else {
                    productList.stream().filter(sp -> StringUtils.isEmpty(sp.getSpdm()) && !StringUtils.isEmpty(sp.getSpmc()))
                            .forEach(m -> {
                                //如果商品名称不为空，且用户选择了名称相同规格型号相同时 进行覆盖操作
                                CsXxProduct sp = spxxListBySpmc.stream().filter(spxx -> spxx.getSpmc().equals(m.getSpmc()) &&
                                                StringUtilsExt.getString(spxx.getGgxh()).equals(StringUtilsExt.getString(m.getGgxh())))
                                        .findAny().orElse(null);
                                if (null != sp) {
                                    m.setId(sp.getId());
                                    updateList.add(m);
                                } else {
                                    insertList.add(m);
                                }
                            });
                }
            }
        }

        //更新
        this.updateBatchById(updateList,1000);

        //插入
        this.saveBatch(insertList,1000);

        return Result.OK("成功新增" + insertList.size() + "条，更新" + updateList.size() + "条！");
    }

    /**
     * 处理税收编码
     * 长于19去掉右边，不够19后边补零
     *
     * @return
     */
    private String operateSsbm(String ssbm) {
        if (org.springframework.util.StringUtils.isEmpty(ssbm)) {
            ssbm = "";
        } else if (ssbm.length() > 19) {
            ssbm = ssbm.substring(0, 19);
        } else if (ssbm.length() < 19) {
            int addLen = 19 - ssbm.length();
            for (int i = 0; i < addLen; i++) {
                ssbm += "0";
            }
        }
        return ssbm;
    }
}
